<?php
namespace common\models;

use common\models\sms\SMS;
use Yii;
use yii\base\Exception;
use yii\db\ActiveRecord;
use yii\web\UploadedFile;

class Functions extends ActiveRecord
{
    public static function getVerifyKey($token = '', $type = '') {
        return md5($token . "_" . $type);
    }

    static function replaceStartFilter($string, $start = 0, $end = 0) {
        $count = mb_strlen($string, 'UTF-8'); //此处传入编码，建议使用utf-8。此处编码要与下面mb_substr()所使用的一致
        if (!$count) {
            return $string;
        }
        if ($end == 0) {
            $end = $count;
        }

        $i = 0;
        $returnString = '';
        while ($i < $count) {
            $tmpString = mb_substr($string, $i, 1, 'UTF-8'); // 与mb_strlen编码一致
            if ($start <= $i && $i < $end) {
                $returnString .= '*';
            } else {
                $returnString .= $tmpString;
            }
            $i ++;
        }
        return $returnString;
    }

    static function  base64_image_content($base64_image_content,$path){
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            //var_dump($result);die;
            $type = $result[2];
            $new_file = $path."/".date('Ymd',time())."/";
            if(!file_exists($new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0777);
            }

            $new_file = $new_file.time().".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
                return '/'.$new_file;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    public static function getRemoteIp() {
        $ip = Yii::$app->request->remoteIP;
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = trim(current($ip));
        }
        return $ip;
    }

    /**
     * pc online 获取IP信息
     * @param $ip
     * @return mixed
     */
    public static function getPcOnlineIpInfo($ip = '')
    {
//        $userInfoUrl = "https://restapi.amap.com/v5/ip?key=bff98d75d2cc2915c9c6bbff556485a7&type=4&ip=$ip";
        $userInfoUrl = "http://whois.pconline.com.cn/ipJson.jsp?callback=testJson&ip={$ip}";
        $result = Functions::request($userInfoUrl);

        $ip_info = trim($result);

        $ip_info = str_replace("if(window.testJson) {testJson(", "", $ip_info);
        $ip_info = str_replace(");}", "", $ip_info);
        $jsonStr = iconv("gbk", "UTF-8", $ip_info);
        $arr = json_decode($jsonStr, true);

        return $arr;
    }

    public static function diffBetweenTwoDays ($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    public static function FormatPs($ps = []) {
        $ranking = [];
        foreach ($ps as $k => $v) {
            $no = $k + 1;
            $ranking[] = $no . "." . $v;
        }

        return implode("\n", $ranking);
    }

    /**
     * 随机一串字母
     * @param int $length
     *
     * @return string
     */
    public static function randLetterNumber($length = 5)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789';
        $randStr = '';
        for ($i = 0; $i < $length; $i ++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $randStr .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }

        return $randStr;
    }

    public static function hiddenPhone($phone = '', $start = 3, $length = 4) {

        return substr_replace($phone, str_repeat("*", $length), $start, $length);
    }


    public function getIpAddressByBaidu($ip = '') {
        if (empty($ip)) {
            $ip = Yii::$app->request->remoteIP;
        }

        $url = "http://api.map.baidu.com/location/ip?ip={$ip}&ak=7SU7NQrnZz6KlzxIsGTZC4XLAmOo0bSU&coor=gcj02";
        $ch = curl_init($url);
        //curl_setopt($ch,CURLOPT_ENCODING ,'utf8');
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
        $location = curl_exec($ch);
        $location = json_decode($location, true);
        curl_close($ch);

        if($location['status'] != 0) return "";
        return $location['content']['address'];

    }


    /**
     * 格式化日期
     * @param string $format
     * @param        $date
     *
     * @return false|string
     */
    public static function formatDate($format = "Y-m-d H:i:s", $date) {
        if ($date == '') {
            return '';
        }
        if (is_numeric($date)) {
            return date($format, $date);
        }
        return date($format, strtotime($date));
    }

    /**
     * 格式化ajax 返回格式
     * @param int    $code
     * @param string $message
     * @param        $data
     *
     * @return array
     */
    public static function formatJson($code = 1000, $message = '', $data = []){
        return ["code" => $code, "message" => $message, "data" => $data];
    }

    public static function formatInside($status = true, $message = '', $data = []) {
        return ['status' => $status, 'message' => $message, 'data' => $data];
    }
    public static function formatRestAPI($status = 0, $msg = '', $data = []) {
        if (empty($data)) {
//            $data = [];
            $data = null;
        }
        return ['status' => $status, 'message' => $msg, 'data' => $data];
    }

    /**
     * @name php获取中文字符拼音首字母
     * @param $str
     * @return null|string
     * @author 潘军伟<panjunwei@ruiec.cn>
     * @time 2015-09-14 17:58:14
     */
    public static function getFirstCharter($str)
    {
        if (empty($str)) {
            return '';
        }
        $fchar = ord($str{0});
        if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
        $s1 = iconv('UTF-8', 'gb2312', $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 && $asc <= -20284) return 'A';
        if ($asc >= -20283 && $asc <= -19776) return 'B';
        if ($asc >= -19775 && $asc <= -19219) return 'C';
        if ($asc >= -19218 && $asc <= -18711) return 'D';
        if ($asc >= -18710 && $asc <= -18527) return 'E';
        if ($asc >= -18526 && $asc <= -18240) return 'F';
        if ($asc >= -18239 && $asc <= -17923) return 'G';
        if ($asc >= -17922 && $asc <= -17418) return 'H';
        if ($asc >= -17417 && $asc <= -16475) return 'J';
        if ($asc >= -16474 && $asc <= -16213) return 'K';
        if ($asc >= -16212 && $asc <= -15641) return 'L';
        if ($asc >= -15640 && $asc <= -15166) return 'M';
        if ($asc >= -15165 && $asc <= -14923) return 'N';
        if ($asc >= -14922 && $asc <= -14915) return 'O';
        if ($asc >= -14914 && $asc <= -14631) return 'P';
        if ($asc >= -14630 && $asc <= -14150) return 'Q';
        if ($asc >= -14149 && $asc <= -14091) return 'R';
        if ($asc >= -14090 && $asc <= -13319) return 'S';
        if ($asc >= -13318 && $asc <= -12839) return 'T';
        if ($asc >= -12838 && $asc <= -12557) return 'W';
        if ($asc >= -12556 && $asc <= -11848) return 'X';
        if ($asc >= -11847 && $asc <= -11056) return 'Y';
        if ($asc >= -11055 && $asc <= -10247) return 'Z';
        return null;
    }


    /**
     * 文件上传方法,支付多字段文件上传
     * @param string $formFields
     * @param string $oldFilePath
     * @param bool   $public        上传到公共文件夹中，随代码提交
     *
     * @return array
     * @throws Exception
     */
    public static function uploadFile($formFields = '', $oldFilePath = '', $public = false)
    {
        //这个文件要创建到web的目录下,文件的绝对路径
        $rootDir = Yii::getAlias('@uploads') . '/';
        $dateDir = $public ? 'public/' : date("Ymd")."/";
        //不为空则上传了新图片，需要删除就图片
        $imgPath = $rootDir . $dateDir;
        $field = [];
        if(is_array($formFields) && !empty($formFields)) {
            foreach ($formFields as $key => $value) {
                $singleField = [
                    'field' => $key,
                    'file_path' => !empty($value) ? $value : '',
                ];
                array_push($field, $singleField);
            }
        } else {
            $field[] = [
                'field' => $formFields,
                'file_path' => !empty($oldFilePath) ? $oldFilePath : '',
            ];
        }


        foreach ($field as $key => $value) {
            $image = UploadedFile::getInstanceByName($value['field']);

            if (!empty($image)) {
                //创建目录并给与777权限
                if (!file_exists($imgPath)) {
                    mkdir($imgPath,0777);
                }
                //获取上传图片后缀名
                $ext = $image->getExtension();
                //生成新图片名称
                $newImageName = md5(time() . rand(10000, 99999)) . '.' . $ext;
                //生成新的图片相对web路径
                $imageName = $imgPath . $newImageName;
                //保存文件函数，在手册上有，将图片保存到本地
                $status = $image->saveAs($imageName, true);
                //如果保存成功
                if ($status !== true) {
                    throw new Exception(false);
                }

                //删除旧图片
                if (!preg_match('/\/default\/images\//', $oldFilePath)) {
                    $oldFileFullPath = $rootDir . $value['file_path'];
                    if (!empty($value['file_path']) && $value['file_path'] != '*' && file_exists($oldFileFullPath)) {
                        @unlink($oldFileFullPath);
                    }
                }
                $field[$key] = [
                    'field' => $value['field'],
                    'file_path' => '/' . $dateDir . $newImageName,
                ];
            }
        }
        if (is_array($formFields)) {
            return $field;
        } else {
            return $field[0]['file_path'];
        }
    }

    /**
     * 删除旧图片
     * @param string $oldPath
     */
    public static function delOldImage($oldPath = '') {
        $rootDir = Yii::getAlias('@uploads');
        if(!empty($oldPath)) {
            $oldFileFullPath = $rootDir . $oldPath;
            if (!empty($oldFileFullPath) && $oldFileFullPath != '*' && file_exists($oldFileFullPath)) {
                @unlink($oldFileFullPath);
            }
        }
    }

    /**
     * 获取Redis 哈希
     * @param array $data
     * @return array
     */
    public static function formatHGetAll($data = []) {
        $count = count($data);
        $result = [];
        for ($i = 0; $i < $count; $i += 2) {
            $result[$data[$i]] = $data[$i+1];
        }
        return $result;
    }

    public static function formatAppUrl($url = '', $protocol = 'http') {
        $url = ltrim($url, $protocol);
        $url = ltrim($url, '/');
        $url = $protocol . "://" . $url;
        return $url;
    }


    public static function sendCode($to = '', $type  = '') {
        $model = new SMS();
        $res = $model->sendCode($to, $type);
        if ($res['code'] == 2000) {
            throw new Exception($res['message']);
        }
    }

    public static function sendNotice($to = '', $content = '', $isEx = true) {
//        return true;
        $model = new SMS();

        $res = $model->sendNotice($to, $content);

        if (!empty($res) && $res['code'] == 2000) {
            if ($isEx) {
                throw new Exception($res['message'], 30001);
            } else {
                return $res['message'];
            }
        }

        return true;
    }

    /**
     * 字符自动填充到指定长度
     * @param int    $numbers   被填充的字符
     * @param int    $addLength 指定长度
     * @param string $addString 填充字符
     *
     * @return string
     */
    public static function addZero($numbers = 0, $addLength = 3, $addString = '0') {
        $numbers = strval($numbers);
        $diff = $addLength - strlen($numbers);
        if($diff > 0) {
            return str_repeat($addString, $diff). $numbers;
        }
        return $numbers;
    }

    /**
     * 下划线转小驼峰
     * @param $str
     *
     * @return mixed
     */
    public static function convertUnderline($str) {
        $str = preg_replace_callback('/([-_]+([a-z]{1}))/i',function($matches) {
            return strtoupper($matches[2]);
        }, $str);
        return $str;
    }

    /**
     * 检查日期格式是否正确
     * @param string $date
     * @return bool
     */
    public static function checkDateTime($date = '') {

        if (empty($date)) {
            return false;
        }
        $strTime = strtotime($date);

        $formatDate = date('Y-m-d H:i:s', $strTime);
        return $date == $formatDate;
    }

    /**
     * 根据开始和结束时间获取时间表 -- Echarts
     * @param null $start
     * @param null $end
     *
     * @return array
     */
    public static function getTimeForEchart($start = null, $end = null)
    {
        if (empty($start)) {
            $start = date('Y-m-d 00:00:00');
        }
        if (empty($end)) {
            $end = date('Y-m-d 23:59:59');
        }
        $startTimestamp = strtotime($start);
        $endTimestamp = strtotime($end);
        $result = [];
        //如果查询日期超过一天
        if ($endTimestamp - $startTimestamp > 24 * 3600) {
            $days = ceil(($endTimestamp - $startTimestamp) / (24 * 60 * 60));
            for ($i = 0; $i < $days; $i ++) {
                $xAxis = date('Y-m-d', $startTimestamp + 24 * 3600 * $i);
                $startTime = date('Y-m-d 00:00:00', $startTimestamp + 24 * 3600 * $i);
                $endTime = date('Y-m-d 23:59:59', strtotime($startTime));
                $result[] = ['xAxis' => $xAxis, 'start' => $startTime, 'end' => $endTime];
            }
        }
        //如果查询日期小于一天则每小时获取一次
        if ($endTimestamp - $startTimestamp <= 24 * 3600) {
            for ($i = 0; $i < 24; $i ++) {
                $xAxis = date('H', $startTimestamp + 3600 * $i);
                $startTime = date('Y-m-d H:00:00', $startTimestamp + 3600 * $i);
                $endTime = date('Y-m-d H:59:59', strtotime($startTime));
                $result[] = ['xAxis' => $xAxis, 'start' => $startTime, 'end' => $endTime];
            }
        }
        return $result;
    }

    /**
     * 利用curl抓取网页，截取网页内容
     * @param $curl
     * @param bool $https
     * @param string $method
     * @param null $data
     * @return mixed
     */
    public static function request($curl, $https = true, $method = "GET",$data = null) {
        $ch = curl_init();//获取资源
        //设置选项
        curl_setopt($ch,CURLOPT_URL,$curl);
        curl_setopt($ch,CURLOPT_HEADER,false);//头部不输出
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//将 curl_exec()获取的信息以文件流的形式返回，而不是直接输出。 是否输出请求地址
        if($https) {//是否进行服务器主机的验证

            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不进行服务器的验证
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);//进行证书验证
        }
        if($method == "POST") {
            curl_setopt($ch,CURLOPT_POST,true);//设置post为true
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//设置url地址的参数
        }
        $content = curl_exec($ch);//得到一个值
        curl_close($ch);//关闭资源
        return $content;
    }

    /**
     * 简单获取用户访问的系统信息
     * @return string
     */
    public static function getSystem() {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if(stristr($user_agent,'Android')) {
            return 'android';
        }
        if(stristr($user_agent,'iPhone')){
            return "iphone";
        }
        if(stristr($user_agent,'Mobile')){
            return "mobile";
        }

        return "pc";
    }

    /**
     * 根据指定时间获取 当天开始和结束日期 统计数据使用
     * @param string $start
     * @param string $end
     * @return mixed
     */
    public static function getDay($start = '', $end = '') {
//        $endDay = Functions::getCommonByKey('month_start_date');

        $endHours = '13:30';

        if (empty($start) && empty($end)) {
            $date = date("Y-m-d");
            $startTime = date("Y-m-d {$endHours}:00",strtotime("-1 day",strtotime($date)));
            $endTime = date("Y-m-d {$endHours}:00",strtotime($date));
        } else {
            $startTime = date("Y-m-d {$endHours}:00",strtotime("-1 day",strtotime($start)));
            $endTime = date("Y-m-d {$endHours}:00",strtotime($end));
        }
        $result['start'] = $startTime;
        $result['end'] = $endTime;
        return $result;

    }

    /**
     * 检查时间是否在指定范围内 可跨天检测
     * @param string $start 09:00
     * @param string $end   21:00
     * @param string $time
     * @return bool
     */
    public static function checkTime($start = '', $end = '', $time = '') {
        if (empty($start) || empty($end)) {
            return true;
        }

        if (empty($time)) {
            $time = date("Y-m-d H:i");
        }

        $startDatetime = date("Y-m-d {$start}:00");
        $endDatetime = date("Y-m-d {$end}:00");

        if ($start <= $end) {
            return $time >= $startDatetime && $time <= $endDatetime;
        } else {
            return !($time < $startDatetime && $time > $endDatetime);
        }
    }

    public static function shortDatetime($datetime = '') {
        if (empty($datetime)) {
            return "--";
        }

        return date("m/d H:i:s", strtotime($datetime));
    }

    /**
     * 获取两个日期的相隔天数
     * @param string $start
     * @param string $end
     * @return float|int
     */
    public static function getDuringDays ($start = '', $end = '') {
        if (empty($end)) {
            $end = date("Y-m-d");
        }

        $second1 = strtotime($start);
        $second2 = strtotime($end);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    public static function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val) {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    static function xmlToArray($xml) {
        if (file_exists($xml)) {
            libxml_disable_entity_loader(false);
            $xml_string = simplexml_load_file($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        } else {
            libxml_disable_entity_loader(true);
            $xml_string = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        }
        $result = json_decode(json_encode($xml_string), true);

        return $result;
    }

    public static function getWechatPaySig($params = [], $secretKey = '') {
        $md5Params = $params;

        ksort($md5Params);
        $tmp = [];
        foreach ($md5Params as $k => $v) {
            $tmp[] = $k . '=' . $v;
        }
        //appid=wxafd19b0dec1abfc0&body=KOKO美妆商品支付&device_info=kokomeizi_mini&mch_id=1530538611&nonce_str=4c9e1428bd64069ccf1adb07d9faf625&key=shanghaiguangdewenhuachuanmei123
        $stringA = implode("&", $tmp);
        $stringA = $stringA . "&key=" . $secretKey;

        $sign = strtoupper(md5($stringA));
        return $sign;
    }

    public static function checkLoginPassword($pass = '') {
        if (empty($pass)) {
            throw new Exception('密码不能为空');
        }

        if (strlen($pass) < 5 || strlen($pass) > 18) {
            throw new Exception("密码长度在5~18位之间");
        }

        # 规则检查 大小写字母 + 数字
        if (!preg_match(Patterns::passwordMatch(), $pass)) {
            throw new Exception("必须包含有大写字母、小写字母、数字");
        }
    }

    public static function checkNumberPassword($pass = '', $length = 6) {
        if (empty($pass)) {
            throw new Exception('支付密码不能为空');
        }

        if (strlen($pass) != 6) {
            throw new Exception('支付密码必须为6位');
        }
        if (!preg_match("/^\d{{$length}}$/", $pass)) {
            throw new Exception('支付密码必须为6位数字');
        }
    }

    //截取长度
    public static function generateCode($length) {
//        $min = pow(10,($length-1));
//        $max = pow(10,$length)-1;
//        return rand($min, $max);

        // 密码字符集，可任意添加你需要的字符
        $chars = str_shuffle(time().'123456789');
        $randStr = '';
        for ($i = 0; $i < $length; $i ++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $randStr .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }

        return $randStr;
    }


    public static function com_create_guid() {
//        return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
//            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
//            mt_rand( 0, 0xffff ),
//            mt_rand( 0, 0x0fff ) | 0x4000,
//            mt_rand( 0, 0x3fff ) | 0x8000,
//            mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
//        );

        return (mt_rand( 0, 0xffff ). mt_rand( 0, 0xffff ).
            mt_rand( 0, 0xffff ).
            mt_rand( 0, 0x0fff ) | 0x4000.
            mt_rand( 0, 0x3fff ) | 0x8000.
            mt_rand( 0, 0xffff ). mt_rand( 0, 0xffff ). mt_rand( 0, 0xffff ));
    }

    public static function diffDateTime($startTime = '', $endTime = '') {

        $result = "";
        $endUnix = strtotime($endTime);
        $startUnix = strtotime($startTime);
        $diff = $endUnix - $startUnix;

        $days = floor($diff / 86400);

        $hoursDiff = $diff - $days * 86400;
        $hours = floor($hoursDiff / 3600);

        $minutesDiff = $hoursDiff - $hours * 3600;
        $minutes = floor($minutesDiff / 60);

        $second = $minutesDiff - $minutes * 60;

        if ($days > 0) {
            $result .= $days . "天";
        }
        if ($hours > 0) {
            $result .= $hours . "时";
        }
        if ($minutes > 0) {
            $result .= $minutes . "分";
        }
        if ($second > 0) {
            $result .= $second . "秒";
        } else {
            $result .= "1秒";
        }

        return $result;
    }

    /**
     * 敏感词过滤，返回结果
     * @param string $string 要过滤的内容
     * @return string $log 处理结果
     */
    public static function sensitive($string){

        $configSensitiveStr = Common::getCommonByKey('sensitive_word');
        $configSensitiveStr = str_replace("，", ",", $configSensitiveStr);
        $list = explode(',',$configSensitiveStr);
        $list = array_filter(array_unique($list));

        $flag = false;
        $count = 0; //违规词的个数
        $sensitiveWord = '';  //违规词
        $stringAfter = $string;  //替换后的内容
        $pattern = "/".implode("|",$list)."/i"; //定义正则表达式
        if(preg_match_all($pattern, $string, $matches)){ //匹配到了结果
            $flag = true;
            $patternList = $matches[0];  //匹配到的数组
            $count = count($patternList);
            $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
            $replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); //把匹配到的数组进行合并，替换使用
            $stringAfter = strtr($string, $replaceArray); //结果替换
        }

        return [$flag,$stringAfter];
//        $log = "原句为 [ {$string} ]<br/>";
//        if($count==0){
//            $log .= "暂未匹配到敏感词！";
//        }else{
//            $log .= "匹配到 [ {$count} ]个敏感词：[ {$sensitiveWord} ]<br/>".
//                "替换后为：[ {$stringAfter} ]";
//        }
//        var_dump($log);die;
//        return $log;
    }

    /**
     * 计算生日
     * @param $birthday
     * @return bool|false|int
     */
    public static function birthday($birthday){

        $age = strtotime($birthday);

        if($age === false){

            return false;

        }

        list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));

        $now = strtotime("now");

        list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));

        $age = $y2 - $y1;

        if((int)($m2.$d2) < (int)($m1.$d1))

            $age -= 1;

        return $age;

    }

    //计算两个坐标(经度，纬度)之间的距离，返回结果为米或者千米
    public static function distance($lat1, $lng1, $lat2, $lng2, $miles = true) {

        $pi80 = M_PI / 180;

        $lat1 *= $pi80;

        $lng1 *= $pi80;

        $lat2 *= $pi80;

        $lng2 *= $pi80;

        $r = 6372.797; // mean radius of Earth in km

        $dLat = $lat2 - $lat1;

        $dLng = $lng2 - $lng1;

        $a = sin($dLat / 2)*sin($dLat / 2)+cos($lat1)*cos($lat2)*sin($dLng / 2)*sin($dLng / 2);

        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));

        $km = $r * $c;

        return ($miles ? ($km * 0.621371192) : $km);

    }

}
